﻿using System;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Pivot;
using System.Windows.Controls.Primitives;

namespace PiviotViewerSLViewer
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            //
            // Get the collection title, and eventually update the page title with it.
            //

            var loader = from r in Observable.FromEventPattern<RoutedEventArgs>(LayoutRoot, "Loaded")
                         from name in GetCollectionTitle(int.Parse((App.Current as App).CollectionIndex))
                         select name;
            loader
                .ObserveOnDispatcher()
                .Subscribe(dtitle =>
                    {
                        TitleTextBox.Text = dtitle;

                        var descrip = from r in Observable.FromEventPattern<RoutedEventArgs>(LayoutRoot, "Loaded")
                                      from name in GetCollectionDescription(int.Parse((App.Current as App).CollectionIndex))
                                      select name;
                        descrip
                            .Where(d => d.Length > 0)
                            .ObserveOnDispatcher()
                            .Subscribe(d =>
                            {
                                var descripButtonPushed = from r in Observable.FromEventPattern<RoutedEventArgs>(DescriptionButton, "Click")
                                                          select r;
                                descripButtonPushed.ObserveOnDispatcher().Subscribe(m =>
                                {
                                    _pop.Child = new CollectionInfoBox(() => _pop.IsOpen = false, dtitle, d);
                                    _pop.VerticalAlignment = VerticalAlignment.Center;
                                    _pop.HorizontalAlignment = HorizontalAlignment.Center;
                                    _pop.Width = double.NaN;
                                    _pop.Height = double.NaN;
                                    _pop.IsOpen = true;
                                });

                                DescriptionButton.Visibility = System.Windows.Visibility.Visible;
                            });
                    });

            //
            // Forward and back buttons need to be implemented!
            //

            _navTracker = new PivotNavagationTracker(PViewer);
            BackButton.Command = _navTracker.MoveBackCommand;
            ForwardButton.Command = _navTracker.MoveForwardCommand;

        }

        /// <summary>
        /// A pop up for this page when we need it.
        /// </summary>
        private Popup _pop = new Popup();

        /// <summary>
        /// Keep track of the navagation guy that keeps a stack for forward and back buttons.
        /// </summary>
        private PivotNavagationTracker _navTracker;

        /// <summary>
        /// Hold onto the cxml collection!
        /// </summary>
        private CxmlCollectionSource _cxml = null;

        /// <summary>
        /// Called when the pivot viewer has loaded itself.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PVLoaded(object sender, System.Windows.RoutedEventArgs e)
        {
            _cxml = new CxmlCollectionSource(new Uri(string.Format("http://deeptalk.phys.washington.edu/PivotWebRenders/{0}/collection.cxml", (App.Current as App).CollectionIndex)));
            _cxml.StateChanged += _cxml_StateChanged;
        }

        /// <summary>
        /// The state of the CXML has changed. We can now deal with it.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _cxml_StateChanged(object sender, CxmlCollectionStateChangedEventArgs e)
        {
            if (e.NewState == CxmlCollectionState.Loaded)
            {
                PViewer.PivotProperties = _cxml.ItemProperties.ToList();
                PViewer.ItemTemplates = _cxml.ItemTemplates;
                PViewer.ItemsSource = _cxml.Items;
            }
        }

        /// <summary>
        /// Access to the web service so we can do call backs, etc. However,
        /// the WS is stateless, so this shouldn't be doing much in the meantime.
        /// </summary>
        private PSWAccess _theWeb = new PSWAccess();

        /// <summary>
        /// Get the collection title. THis is a proxy to make the above code a little cleaner.
        /// </summary>
        private IObservable<string> GetCollectionTitle(int id)
        {
            return _theWeb.GetCollectionName(id);
        }

        /// <summary>
        /// Get the collection title. THis is a proxy to make the above code a little cleaner.
        /// </summary>
        private IObservable<string> GetCollectionDescription(int id)
        {
            return _theWeb.GetCollectionDescription(id);
        }
    }
}
